package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.advice.RecordLogAnno;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.pojo.StuQueryParam;
import com.itheima.pojo.Student;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result pageStu(StuQueryParam QueryParam) {
        PageResult<Student> studentPageResult = studentService.pageStu(QueryParam);
        log.info("学生列表分页查询");
        return Result.success(studentPageResult);
    }
    @RecordLogAnno
    @DeleteMapping("/{ids}")
    public Result deleteById(@PathVariable List<Integer> ids) {
        studentService.removeBatchByIds(ids);
        log.info("学生列表数据删除");
        return Result.success();
    }
    @RecordLogAnno
    @PostMapping
    public Result save(@RequestBody Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentService.save(student);
        log.info("学生列表新增");
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        log.info("学生列表数据回显");
        return Result.success(student);
    }
    @RecordLogAnno
    @PutMapping
    public Result updateStu(@RequestBody Student student){
        student.setUpdateTime(LocalDateTime.now());
       studentService.updateById(student);
       log.info("学生列表信息修改");
       return Result.success();
    }
    @RecordLogAnno
    @PutMapping("/violation/{id}/{score}")
    public Result punishViolation(@PathVariable Integer id, @PathVariable Integer score){
        LambdaUpdateWrapper<Student> updateWrapper = new LambdaUpdateWrapper<>();
        // 1. 使用 setSql 实现 violation_count = violation_count + 1
        updateWrapper.setSql("violation_count = violation_count + 1");
        // 2. 使用 setSql 实现 violation_score = violation_score + score
        updateWrapper.setSql("violation_score = violation_score + " + score);
        updateWrapper.eq(Student::getClazzId,id);
        studentService.update(updateWrapper);
        log.info("学生违纪处理");
        return Result.success();
    }

}
